from urllib import request,parse
import json
import time,random
import hashlib

def translate(word):
	url = 'http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule'
	
	m = hashlib.md5()  #生成加密串
    #根据md5的方式：md5(u + d + f + c)拼接字符串生成sign参数
	u = 'fanyideskweb'
	d = word
	f = str(int(time.time()*1000) + random.randint(1, 10))
	c = "ebSeFb%=XZ%T[KZ)c(sy!"
	m.update((u+d+f+c).encode('utf-8'))
	
	data = {
		'i':d,
		'from': 'AUTO',
		'to': 'AUTO',
		'smartresult': 'dict',
		'client': u,
		'salt': f,
		'sign': m.hexdigest(),
		'ts': '1551689742563',
		'bv': '617939f69fb18f112aa988d6038ae43f',
		'doctype': 'json',
		'version': '2.1',
		'keyfrom': 'fanyi.web',
		'action': 'FY_BY_REALTIME',
		'typoResult': 'false'
	}
	#data 参数如果要传必须传 bytes（字节流）类型的，如果是一个字典，可以先用 urllib.parse.urlencode() 编码
	data = parse.urlencode(data)

	headers = {
		'Content-Length':len(data),
		'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
		'Cookie': 'OUTFOX_SEARCH_USER_ID=993508058@10.168.1.247; OUTFOX_SEARCH_USER_ID_NCOO=1350139529.826177; JSESSIONID=aaaA_XSZgkkjUfFrGlMFw; ___rl__test__cookies=1545792032451',
		'Origin': 'http://fanyi.youdao.com',
		'Referer': 'http://fanyi.youdao.com/',
		'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)        AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36'
	}

	req = request.Request(url,data=bytes(data,encoding="utf-8"),headers=headers)
	res = request.urlopen(req)

	str_json = res.read().decode('utf-8') # json
	myjson = json.loads(str_json) # 把json转字典
	#print(myjson)
	try:
		for vo in myjson['smartResult']['entries']:
			print(vo,end='')
	except Exception as err:
		#print(err)
		print("对不起，没有找到您需要翻译的单词...")

if __name__ == '__main__':
	
	while True:
		word = input("请输入想要翻译的单词(按q退出...)：")
		if word == 'q':
			break
		translate(word)
	print("感谢您的使用！")
